#!/bin/bash
# shell script to run a command if a series of hosts are all unreachable.
# it uses a lock file to keep it from running until all hosts are once
# again reachable. Definition of 'unreachable' is 5 out of 10 packets lost 
# per host.
#
# Author: Nathan Hubbard
# URL: http://code.google.com/p/n8foo
# -------------------------------------------------------------------------

# add ip / hostname separated by white space
HOSTS="google.com yahoo.com yourserver.com"
# script to run
TORUN="cycle_cablemodem.exp"

# lockfile, used to detect if the other command has already been run
LOCKFILE="/tmp/pinger.lock"


TOTAL=0
for HOST in $HOSTS
do
  COUNT=`ping -c 10 $HOST | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }'`
  if [ $COUNT -le 5 ]; then
    TOTAL=$[TOTAL+1]
  fi
done

# all 3 hosts are down
if [ $TOTAL -eq 3 ]; then
        # check for lock file and exit
        if [ -e $LOCKFILE ]; then
                exit
        else
                # set up a lockfile
                touch $LOCKFILE
        fi
        # time to run the script
        $TORUN
else
        # if everything's back, remove the lock file
        rm -f $LOCKFILE
        exit
fi
